<template>
  <div class="department-management-container" @click="hideContextMenu">
    <el-row :gutter="20">
      <!-- 左侧树形部门结构 -->
      <el-col :span="8">
        <el-card>
          <div class="header">
            <el-input
                v-model="searchQuery"
                placeholder="搜索部门"
                class="search-input"
                clearable
                @clear="resetTreeData"
                @input="fetchDepartments"
            ></el-input>
          </div>
          <el-tree
              ref="departmentTree"
              :data="treeData"
              node-key="id"
              :props="defaultProps"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
              @node-contextmenu="handleNodeContextMenu"
          ></el-tree>
        </el-card>
      </el-col>

      <!-- 右侧详细信息 -->
      <el-col :span="16">
        <el-card v-if="selectedDepartment">
          <h2>{{ selectedDepartment.name }}</h2>
          <el-form label-width="100px">
            <el-form-item label="部门名称">
              <el-input v-model="selectedDepartment.name"></el-input>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="selectedDepartment.description"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="selectedDepartment.email"></el-input>
            </el-form-item>
          </el-form>
          <div class="save-button-container">
            <el-button type="primary" @click="saveDepartmentChanges">保存</el-button>
          </div>
        </el-card>
        <el-card v-else>
          <p>点击左侧部门查看详细信息</p>
        </el-card>
      </el-col>
    </el-row>

    <!-- 右键菜单 -->
    <div v-if="contextMenuVisible" :style="contextMenuStyle" class="context-menu">
      <el-button type="text" @click="deleteDepartment(contextMenuData.id)">删除</el-button>
      <el-button type="text" @click="openAddDialog(contextMenuData)">添加</el-button>
    </div>

    <!-- 添加部门弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="currentDepartment" :rules="rules" ref="departmentForm" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="currentDepartment.name"></el-input>
        </el-form-item>

        <el-form-item label="部门描述" prop="description">
          <el-input v-model="currentDepartment.description"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentDepartment.email"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveDepartment">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      treeData: [
        {
          id: 1,
          name: '公司总部',
          description: '管理整个公司',
          email: 'hq@example.com',
          children: [
            {
              id: 2,
              name: '研发部',
              description: '负责产品研发',
              email: 'dev@example.com',
              children: [],
            },
            {
              id: 3,
              name: '市场部',
              description: '负责市场推广',
              email: 'marketing@example.com',
              children: [],
            },
          ],
        },
      ], // 本地模拟的树形部门数据
      selectedDepartment: null, // 当前选中的部门信息
      searchQuery: '', // 搜索关键字
      dialogVisible: false, // 弹窗可见性
      dialogTitle: '', // 弹窗标题
      currentDepartment: {
        id: null,
        name: '',
        description: '',
        email: '',
      }, // 当前编辑的部门信息
      rules: {
        name: [{required: true, message: '请输入部门名称', trigger: 'blur'}],
        description: [{required: true, message: '请输入部门描述', trigger: 'blur'}],
        email: [{required: true, message: '请输入邮箱', trigger: 'blur', type: 'email'}],
      },
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      nextId: 4, // 用于生成新部门的 ID
      contextMenuVisible: false, // 右键菜单是否可见
      contextMenuPosition: {x: 0, y: 0}, // 右键菜单的位置
      contextMenuData: null, // 右键菜单操作的数据
    };
  },
  methods: {
    // 获取部门树形数据（此处为本地模拟数据）
    fetchDepartments() {
      this.treeData = this.filterDepartments(this.treeData, this.searchQuery);
    },

    // 点击部门节点查看详细信息
    handleNodeClick(node) {
      this.selectedDepartment = node;
    },

    // 右键点击事件处理
    handleNodeContextMenu(event, data) {
      event.preventDefault(); // 阻止默认右键菜单
      this.contextMenuPosition = {x: event.clientX, y: event.clientY};
      this.contextMenuData = data;
      this.contextMenuVisible = true;
    },

    // 隐藏右键菜单
    hideContextMenu() {
      this.contextMenuVisible = false;
    },

    // 打开添加部门弹窗
    openAddDialog(parentNode) {
      this.dialogTitle = '添加部门';
      this.currentDepartment = {
        id: this.nextId++, // 使用递增 ID 模拟
        parentId: parentNode ? parentNode.id : null, // 关联父部门ID
        name: '',
        description: '',
        email: '',
      };
      this.dialogVisible = true;
    },

    // 保存部门信息
    handleSaveDepartment() {
      this.$refs.departmentForm.validate((valid) => {
        if (valid) {
          if (this.currentDepartment.parentId) {
            // 添加到对应父部门下
            const parentNode = this.findDepartmentById(this.treeData, this.currentDepartment.parentId);
            parentNode.children.push({...this.currentDepartment});
          } else {
            // 新增顶级部门
            this.treeData.push({...this.currentDepartment});
          }
          this.dialogVisible = false;
          this.resetTreeData(); // 刷新树形结构
        }
      });
    },

    // 删除部门
    deleteDepartment(id) {
      this.treeData = this.removeDepartmentById(this.treeData, id);
      this.selectedDepartment = null; // 清空选中的部门信息
    },

    // 查找部门
    findDepartmentById(departments, id) {
      for (let department of departments) {
        if (department.id === id) {
          return department;
        } else if (department.children && department.children.length > 0) {
          const result = this.findDepartmentById(department.children, id);
          if (result) return result;
        }
      }
      return null;
    },

    // 递归删除部门
    removeDepartmentById(departments, id) {
      return departments.filter((department) => {
        if (department.children && department.children.length > 0) {
          department.children = this.removeDepartmentById(department.children, id);
        }
        return department.id !== id;
      });
    },

    // 递归过滤部门（根据名称）
    filterDepartments(departments, query) {
      return departments
          .map((department) => {
            if (department.name.includes(query)) {
              return department;
            } else if (department.children && department.children.length > 0) {
              const filteredChildren = this.filterDepartments(department.children, query);
              if (filteredChildren.length > 0) {
                return {...department, children: filteredChildren};
              }
            }
            return null;
          })
          .filter((department) => department !== null);
    },

    // 重置部门树数据
    resetTreeData() {
      this.treeData = [
        {
          id: 1,
          name: '公司总部',
          description: '管理整个公司',
          email: 'hq@example.com',
          children: [
            {
              id: 2,
              name: '研发部',
              description: '负责产品研发',
              email: 'dev@example.com',
              children: [],
            },
            {
              id: 3,
              name: '市场部',
              description: '负责市场推广',
              email: 'marketing@example.com',
              children: [],
            },
          ],
        },
      ];
    },

    // 保存按钮点击事件，保存当前修改的部门信息
    saveDepartmentChanges() {
      this.$message.success('部门信息已更新');
    },
  },
  computed: {
    // 动态计算右键菜单的样式
    contextMenuStyle() {
      return {
        position: 'absolute',
        top: `${this.contextMenuPosition.y}px`,
        left: `${this.contextMenuPosition.x}px`,
        zIndex: 1000,
        backgroundColor: '#fff',
        border: '1px solid #ccc',
        boxShadow: '0 2px 12px rgba(0,0,0,0.1)',
        padding: '10px',
      };
    },
  },
};
</script>

<style scoped>
.department-management-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.search-input {
  width: 100%;
  margin-bottom: 10px;
}

.save-button-container {
  text-align: center;
  margin-top: 20px;
}

.context-menu {
  width: 160px;
  border-radius: 4px;
  background-color: white;
}

.context-menu .el-button {
  display: block;
  width: 100%;
  text-align: left;
}

.el-col {
  padding: 10px;
}
</style>
